package com.wwmz.proxy.pattern.dbroute.dynamicproxy;

import com.wwmz.proxy.pattern.dbroute.staticproxy.DynamicDataSourceEntity;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wumz on 2020/9/21 18:25
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object object = method.invoke(target, args);
        after();
        return object;
    }

    public void before() throws Exception {
        System.out.println("Proxy before Method");
        Long time = (Long)target.getClass().getMethod("getCreateTIme").invoke(target);
        Integer integer = Integer.valueOf(yearFormat.format(new Date(time)));
        System.out.println("动态代理类自动分配到【DB_" +  integer + "】数据源处理数据" );
        DynamicDataSourceEntity.set(integer);
    }

    public void after(){
        System.out.println("Proxy after Method");
    }
}
